/**
 * 图库分类管理
 */
var express = require('express');
const Result = require('../lib/Result');
const isRule = require('../util/isRule');
const ImageClass = require('../db/models/image/image_class');
const Image = require('../db/models/image/image');
const sequelize = require('../db/sequelize');
var router = express.Router();
/**
 * 指定分类下的图片列表,token需要62号权限，或11号权限，或172号权限,或super==1
 */
router.get("/:id/image/:page", (req, res) => {
    let token = req.auth
    let id=req.params.id
    let page=Number(req.params.page)
    let limit=req.query.limit?Number(req.query.limit):10
    // console.log("limit:",limit);
    if (isRule(token.rule, [62,11,172], res, token.super)) {
        ImageClass.getImagebyImageClass(limit,page,id).then(value=>{
            res.json(Result.success(value))
        })
    }
})
/**
 * 图库列表,token需要63号权限，或11号权限，或172号权限,或super==1
 */
router.get("/:page", (req, res) => {
    let token = req.auth
    if (isRule(token.rule, [63,11,172], res, token.super)) {
        ImageClass.findAll({
            include:[
                {
                    model:Image,
                    attributes:[
                        [
                            sequelize.fn('COUNT',sequelize.col("Images.id")),"images_count"
                        ]
                    ],
                }
            ],
            group:"id"
        }).then(row=>{
            let json={}
            json["totalCount"]=row.length
            json["list"]=[]
            row.forEach(value=>{
                json.list.push(value.toJSON())
            })
            res.json(Result.success(json))
        })
    }
})
/**
 * 删除图库分类，tiken需要66号权限，或11号权限，或172号权限,或super==1
 */
router.post("/:id/delete",(req, res) => {
    let token = req.auth
    if (isRule(token.rule, [66,11,172], res, token.super)) {
        ImageClass.deleteImageClass(req.params.id).then(value=>{
            res.json(Result.success(true))
        })
    }
})

/**
 * 修改图库分类，tiken需要65号权限，或11号权限，或172号权限,或super==1
 */
router.post("/:id",(req, res) => {
    let token = req.auth
    if (isRule(token.rule, [65,11,172], res, token.super)) {
        let name=req.body.name;
        let order=req.body.order
        if (name==undefined||order==undefined) {
            return res.json(Result.validateFailed())
        }
        ImageClass.updateImageClass(req.params.id,name,order).then(value=>{
            res.json(Result.success(true))
        })
    }
})
/**
 * 添加图库分类，tiken需要64号权限，或11号权限，或172号权限,或super==1
 */
router.post("",(req, res) => {
    let token = req.auth
    if (isRule(token.rule, [64,11,172], res, token.super)) {
        ImageClass.addImageClass(req.body.name,req.body.order).then(value=>{
            res.json(Result.success(value.toJSON()))
        })
    }
})
module.exports=router